package com.coolweather.android;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Weatherinfo extends AppCompatActivity {
    private String weatherId;
    private Weather weatherobj;
    private TextView cityName;
    private Handler mHandler = new Handler();

    public DrawerLayout drawerLayout;

    public SwipeRefreshLayout swipeRefresh;

    private ScrollView weatherLayout;

    private Button navButton;

    private TextView titleCity;

    private TextView titleUpdateTime;

    private TextView degreeText;

    private TextView weatherInfoText;

    private LinearLayout forecastLayout;

    private TextView aqiText;

    private TextView pm25Text;

    private TextView comfortText;

    private TextView carWashText;

    private TextView sportText;

    private ImageView bingPicImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weatherinfo);
        weatherId = getIntent().getStringExtra("weatherid");
        Log.d("info", weatherId);
        String address = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
        Log.d("info", address);
        queryDataFromServer(address);
        cityName = (TextView) findViewById(R.id.title_city);
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.white);
        //SwipeRefreshLayout刷新组件
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        queryDataFromServer(address);
                        swipeRefresh.setRefreshing(false);
                    }
                },1000);
            }
        });
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                drawerLayout.openDrawer(GravityCompat.START);
                Intent intent = new Intent(Weatherinfo.this, MainActivity.class);
                startActivity(intent);
                Weatherinfo.this.finish();
            }
        });
        //获取共享数据
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Weatherinfo.this);
//        String weatherString = prefs.getString("weather",null);
    }

    /**
     * 显示方法
     */
    private void displayWeather() {
        Log.d("weainfo",weatherobj.basic.cityName);
        cityName.setText(weatherobj.basic.cityName);
        String cityName = weatherobj.basic.cityName;
        String updateTime = weatherobj.basic.update.updatetime.split(" ")[1];
        String degree = weatherobj.now.temperature + "℃";
        String weatherInfo = weatherobj.now.more.info;
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forecastLayout.removeAllViews();
        for (Forecast forecast : weatherobj.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
            TextView dateText = (TextView) view.findViewById(R.id.date_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            forecastLayout.addView(view);
        }
        if (weatherobj.aqi != null) {
            aqiText.setText(weatherobj.aqi.city.aqi);
            pm25Text.setText(weatherobj.aqi.city.pm25);
        }
        String comfort = "舒适度：" + weatherobj.suggestion.comfort.info;
        String carWash = "洗车指数：" + weatherobj.suggestion.carWash.info;
        String sport = "运行建议：" + weatherobj.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
    }

    /**
     * 请求服务器数据
     * @param address  请求地址
     */
    public void queryDataFromServer(String address) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Toast.makeText(Weatherinfo.this, "加载失败", Toast.LENGTH_LONG).show();
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responseData = response.body().string();
                            try {
//                                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(Weatherinfo.this).edit();
//                                editor.putString("weather",responseData);
//                                editor.apply();
                                parseWeatherInfo(responseData);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        displayWeather();
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析json天气数据
     * @param responseData
     */
    private void parseWeatherInfo(String responseData) throws JSONException {
        JSONObject firstlevel = new JSONObject(responseData);//responseData转化为JsonObject
        JSONArray jsonArray = firstlevel.getJSONArray("HeWeather");//解析jsonArry
        String weatherContent  = jsonArray.getJSONObject(0).toString();
        Log.d("info",weatherContent);
        weatherobj = new Gson().fromJson(weatherContent,Weather.class);
        Log.d("info",weatherobj.basic.cityName);
    }
}